import {Login} from '^/login'

const state = {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || null) || {}
}
const mutations = {
    SET_TOKEN: (state, token) => {
       state.token = token
       localStorage.setItem('token', token)
    },
 
    CLEAR_TOKEN: (state) => {
       state.token = ''
       state.userInfo = ''
 
       localStorage.clear()
    },
 
    SET_USERINFO: (state, userInfo) => {
       state.userInfo = userInfo
       localStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
}
const actions = {
    login({commit}, loginForm) {
        return new Promise((resolve, reject) => {
            Login(loginForm).then(res => {
                commit('SET_TOKEN', res.data.token)
                commit('SET_USERINFO', res.data.userInfo)
                resolve()
            }).catch(err => {
                console.log("异常结果", err)
                reject(err)
            })
        })
    },
    logout({commit}) {
        commit('CLEAR_TOKEN')
    },
 
    // 获取用户信息
    // async getUserInfo({commit}) {
    //     const {code, data} = await GetUserinfo()
    
    //     console.log('获取用户信息', data)
    //     if (+code === 200) {
    //         commit('SET_USERINFO', data.userInfo)
    
    //         // 如果是后台管理系统，获取权限和菜单
    //         // commit('SET_MENUS', data)
    
    //         return Promise.resolve(data)
    //     }
    // },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}